package com.powerunion.extjs.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.powerunion.extjs.BasePara;
import com.powerunion.extjs.ListRange;
import com.powerunion.extjs.MetaData;
import com.powerunion.extjs.XmlParser;

public class ComboDataLoader extends DbDataLoader {
	
	public ComboDataLoader(BasePara paravo){
		super(paravo);
	}
	
	public void wrapSql() throws Exception{ 
		XmlParser parser = new XmlParser();
		this.paravo.setXmlFileName("combo_sql_config.xml");
		parser.loadSql(this.paravo);
		this.paravo.addWhereSql();
		this.paravo.addOrderSql();
	}
	
	public void collectToMap() {
		ArrayList al = null;
		HashMap map = null;
		String[] colNameArray = convert.contvertColumnName( this.paravo.getSql());
//		colNameArray[0]="text";
//		colNameArray[1]="value";		
		if (!rs.isEmpty()) {
			al = new ArrayList();
			for (Iterator it = rs.iterator(); it.hasNext();) {
				
				Map obj = (Map) it.next();
				map = new HashMap();
				for (int i = 0; i < colNameArray.length; i++) {
					String tag = colNameArray[i].toUpperCase();
					Object value = obj.get(tag);
					if(i==0){
						map.put("text", value);
					}else if(i==1){
						map.put("value", value);
					}else{
						map.put(tag, value);
					}
					
				}
				al.add(map);
			}
		}
		range = new ListRange();
		range.setData(al);
		range.setTotalSize(this.totalCount);
		this.setMetaData(colNameArray);
	}
	
	private void setMetaData(String[] colNameArray){
		ArrayList al = new ArrayList();
		HashMap map=null;
		for(int k=0;k<colNameArray.length;k++){
			map=new HashMap();
			map.put("name", colNameArray[k]);
			map.put("mapping", colNameArray[k]);
			al.add(map);
		}
		MetaData meta = new MetaData();
		meta.setId("value");
		meta.setFields(al);
		range.setMetaData(meta);
	}
}
